package com.snapan.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@Configuration
// 扫描 ES Repository 接口所在的包
@EnableElasticsearchRepositories(basePackages = "com.snapan.es.repository")
public class ElasticsearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 构建客户端配置
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200") // ES 服务器地址
                .withConnectTimeout(5000) // 连接超时时间（毫秒）
                .withSocketTimeout(30000) // Socket 读写超时时间（毫秒）
                .build();
        // 创建 RestHighLevelClient
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean(name = "elasticsearchTemplate")
    public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient restHighLevelClient) {
        // 创建 ElasticsearchRestTemplate，用于操作 ES
        return new ElasticsearchRestTemplate(restHighLevelClient);
    }
}
